package com.test.utils;

import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class MysqlUtils {

    private static Properties properties;

    //定义一个变量 用来记录数据库连接池对象
    private static DataSource ds;

    //由于Druid不会像C3P0那样自动读取配置文件 所以我们使用静态代码块读取配置文件并给数据库连接池赋值
    static {
        try {
            properties = PropUtil.getProperties(PropUtil.MARAIDB_NAME);
            //加载properties配置文件  这里地址写到src的上一级即可
            //数据库连接池配置 使用DruidDataSourceFactory工厂来创建Druid连接池
            ds = getDataSource(properties.getProperty("mariadb.url"));
            System.out.println("初始化mysql data source !!!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static HikariDataSource getDataSource(String url) {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName(properties.getProperty("mariadb.driver-class-name"));
        hikariDataSource.setJdbcUrl(url);
        hikariDataSource.setUsername(properties.getProperty("mariadb.username"));
        hikariDataSource.setPassword(properties.getProperty("mariadb.password"));
        hikariDataSource.setLeakDetectionThreshold(5000);
        hikariDataSource.setIdleTimeout(60000);
        hikariDataSource.setConnectionTimeout(60000);
        hikariDataSource.setValidationTimeout(3000);
        hikariDataSource.setMaxLifetime(60000);
        hikariDataSource.setMinimumIdle(10);
        hikariDataSource.setMaximumPoolSize(65);
        hikariDataSource.setPoolName("TxnDatabasePool");
        hikariDataSource.setLeakDetectionThreshold(5000);
        hikariDataSource.setConnectionTestQuery("SELECT 1 FROM DUAL");
        return hikariDataSource;
    }

    //后面基本跟C3P0简单工具类基本一致

    /**
     * 获取数据库连接Connection
     *
     * @return
     */
    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 释放资源
    public static void release(Connection conn, Statement stat, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stat != null) {
                    stat.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
